package com.rybbaby.tss.core.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import com.rybbaby.tss.platform.initializer.SysConfigInitializer;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 七牛云存储服务端文件上传的工具类
 */
public class QiNiuUtil {

    private static Logger logger = Logger.getLogger(QiNiuUtil.class);

    private static UploadManager uploadManager = null;

    public enum QiNiuZone {
        华东(Zone.zone0()),
        华北(Zone.zone1()),
        华南(Zone.zone2()),
        北美(Zone.zoneNa0());

        private Zone value;

        QiNiuZone(Zone zone) {
            this.value = zone;
        }

        public Zone value() {
            return this.value;
        }
    }

    /**
     * 七牛云存储操作回调接口
     */
    public static interface QiNiuCallback {
        void execute(Object result);
    }

    /**
     * 七牛云存储上传完之后的回调
     */
    public static abstract class QiNiuUploadCallback implements QiNiuCallback {
        public abstract void execute(Object ret);
    }

    /**
     * 七牛云存储上传完之后的回调
     */
    public static abstract class QiNiuDeleteFileCallback implements QiNiuCallback {
        public abstract void execute(Object response);
    }

    /**
     * 上传文件到七牛服务器
     *
     * @param file 需要上传的本地文件
     * @return
     */
    public static DefaultPutRet upload(File file) {
        //获取配置信息
        QiNiuConfig qiNiuConfig = new QiNiuConfig(null).invoke();
        if (qiNiuConfig.is()) {
            return null;
        }
        String key = DateUtil.format("yyyyMMddHHmmss") + "_" + file.getName(),//默认不指定key的情况下，以文件内容的hash值作为文件名
                localFilePath = file.getPath();//本地需要上传文件的路径
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(qiNiuConfig.getZone());
        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        String bucket = qiNiuConfig.getBucket();
        String upToken = auth.uploadToken(bucket);
        String localTempDir = Paths.get(System.getProperty("java.io.tmpdir"), bucket).toString();
        try {
            //设置断点续传文件进度保存目录
            FileRecorder fileRecorder = new FileRecorder(localTempDir);
            if (uploadManager == null) {
                uploadManager = new UploadManager(cfg, fileRecorder);
            }
            try {
                Response response = uploadManager.put(localFilePath, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                logger.info(putRet.key);
                logger.info(putRet.hash);
                return putRet;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void upload(File file, QiNiuUploadCallback callback) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        cachedThreadPool.execute(() -> {
            //获取配置信息
            QiNiuConfig qiNiuConfig = new QiNiuConfig(callback).invoke();
            if (qiNiuConfig.is()) {
                return;
            }
            String key = DateUtil.format("yyyyMMddHHmmss") + "_" + file.getName(),//默认不指定key的情况下，以文件内容的hash值作为文件名
                    localFilePath = file.getPath();//本地需要上传文件的路径
            //构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(qiNiuConfig.getZone());
            Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
            String bucket = qiNiuConfig.getBucket();
            String upToken = auth.uploadToken(bucket);
            String localTempDir = Paths.get(System.getProperty("java.io.tmpdir"), bucket).toString();
            try {
                //设置断点续传文件进度保存目录
                FileRecorder fileRecorder = new FileRecorder(localTempDir);
                if (uploadManager == null) {
                    uploadManager = new UploadManager(cfg, fileRecorder);
                }
                try {
                    Response response = uploadManager.put(localFilePath, key, upToken);
                    //解析上传成功的结果
                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                    logger.info(putRet.key);
                    logger.info(putRet.hash);
                    callback.execute(putRet);
                    return;
                } catch (QiniuException ex) {
                    Response r = ex.response;
                    System.err.println(r.toString());
                    try {
                        System.err.println(r.bodyString());
                    } catch (QiniuException ex2) {
                        //ignore
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            callback.execute(null);
        });
    }

    /**
     * 删除七牛云存储空间的文件
     *
     * @param key
     * @param callback
     */
    public static void delete(String key, QiNiuDeleteFileCallback callback) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        cachedThreadPool.execute(() -> {
            //获取配置信息
            QiNiuConfig qiNiuConfig = new QiNiuConfig(callback).invoke();
            if (qiNiuConfig.is()) {
                return;
            }
            Zone zone = qiNiuConfig.getZone();
            String accessKey = qiNiuConfig.getAccessKey();
            String secretKey = qiNiuConfig.getSecretKey();
            String bucket = qiNiuConfig.getBucket();
            //构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(zone);
            Auth auth = Auth.create(accessKey, secretKey);
            BucketManager bucketManager = new BucketManager(auth, cfg);
            try {
                Response result = bucketManager.delete(bucket, key);
                callback.execute(result);
            } catch (QiniuException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 七牛云存储配置参数
     */
    private static class QiNiuConfig {
        private boolean myResult;
        private QiNiuCallback callback;
        private String accessKey;
        private String secretKey;
        private String bucket;
        private Zone zone;

        public QiNiuConfig(QiNiuCallback callback) {
            this.callback = callback;
        }

        boolean is() {
            return myResult;
        }

        public String getAccessKey() {
            return accessKey;
        }

        public String getSecretKey() {
            return secretKey;
        }

        public String getBucket() {
            return bucket;
        }

        public Zone getZone() {
            return zone;
        }

        public QiNiuConfig invoke() {
            this.accessKey = SysConfigInitializer.getConfigValueByConfigName("qiniu.accessKey", "").toString();
            this.secretKey = SysConfigInitializer.getConfigValueByConfigName("qiniu.secretKey", "").toString();
            this.bucket = SysConfigInitializer.getConfigValueByConfigName("qiniu.bucket", "").toString();
            String zone = SysConfigInitializer.getConfigValueByConfigName("qiniu.zone", "").toString();
            boolean paramsIsSeted = true;
            if (StringUtils.isBlank(this.accessKey)) {
                paramsIsSeted = false;
                logger.error("未设置系统参数：qiniu.accessKey");
            }
            if (StringUtils.isBlank(this.secretKey)) {
                paramsIsSeted = false;
                logger.error("未设置系统参数：qiniu.secretKey");
            }
            if (StringUtils.isBlank(zone)) {
                paramsIsSeted = false;
                logger.error("未设置系统参数：qiniu.zone");
            }
            if (!paramsIsSeted) {
                callback.execute(null);
                myResult = true;
                return this;
            }
            this.zone = QiNiuZone.valueOf(zone).value();
            if (this.zone == null) {
                logger.error("系统参数：qiniu.zone 取值错误，目前仅支持如下几个值：华东、华北、华南、北美");
                callback.execute(null);
            }
            this.myResult = false;
            return this;
        }
    }
}
